import { defineStore } from 'pinia'
import { getFiles, deleteFile as apiDeleteFile, uploadFile as apiUploadFile } from '../services/api'

// 定义科室store
export const useDepartmentsStore = defineStore('departments', {
  state: () => ({
    // 科室列表
    departments: [
      { id: 1, name: '大气办' },
      { id: 2, name: '规划科' },
      { id: 3, name: '协调科' },
      { id: 4, name: '办公室' },
      { id: 5, name: '建设科' },
      { id: 6, name: '财务科' }
    ],
    // 当前选中的科室，null表示所有科室
    currentDepartment: null,
    // 文件列表
    files: [],
    // 加载状态
    loading: false,
    // 错误信息
    error: null
  }),
  getters: {
    // 获取当前科室的文件
    filteredFiles() {
  if (this.currentDepartment === null) {
    return this.files;
  }
  // 使用department_id而不是departmentId，与API返回的数据格式保持一致
  return this.files.filter(file => file.department_id === this.currentDepartment);
},
    // 获取科室名称
    getDepartmentName() {
      return (id) => {
        if (id === null) return '全局文件';
        const dept = this.departments.find(d => d.id === id);
        return dept ? dept.name : '未知科室';
      };
    }
  },
  actions: {
    // 设置当前科室
    setCurrentDepartment(id) {
      this.currentDepartment = id;
      // 获取对应科室的文件
      this.fetchFiles();
    },
    // 从API获取文件
    async fetchFiles() {
      this.loading = true;
      this.error = null;
      try {
        const params = this.currentDepartment ? { department_id: this.currentDepartment } : {};
        const response = await getFiles(params);
        this.files = response.data.files;
      } catch (err) {
        this.error = '获取文件失败: ' + (err.message || '未知错误');
        console.error('获取文件失败:', err);
      } finally {
        this.loading = false;
      }
    },
    // 添加新文件
    async addFile(formData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await apiUploadFile(formData);
        // 添加到文件列表
        this.files.push(response.data);
        return response.data;
      } catch (err) {
        this.error = '上传文件失败: ' + (err.message || '未知错误');
        console.error('上传文件失败:', err);
        throw err;
      } finally {
        this.loading = false;
      }
    },
    // 删除文件
    async deleteFile(id) {
      this.loading = true;
      this.error = null;
      try {
        await apiDeleteFile(id);
        // 从列表中删除
        this.files = this.files.filter(file => file.id !== id);
      } catch (err) {
        this.error = '删除文件失败: ' + (err.message || '未知错误');
        console.error('删除文件失败:', err);
        throw err;
      } finally {
        this.loading = false;
      }
    }
  }
})